import React, { useState, useEffect } from "react";
import {
  StyleSheet,
  View,
  Text,
  ScrollView,
  TextInput,
  Pressable,
} from "react-native";
import { useLocalSearchParams, Stack, useRouter } from "expo-router";
import { SafeAreaView } from "react-native-safe-area-context";
import { Ionicons } from "@expo/vector-icons";
import { getQuestionById, getQuestionsByCategory, difficulties } from "@/mocks/questions";
import {Question} from "@/types/question";
import { useUserStore } from "@/store/user-store";
import { useTheme } from "@/hooks/useTheme";
import Button from "@/components/Button";

export default function QuestionDetailScreen() {
  const { id } = useLocalSearchParams<{ id: string }>();
  const router = useRouter();
  const [question, setQuestion] = useState<Question | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [userAnswer, setUserAnswer] = useState("");
  const [showAnswer, setShowAnswer] = useState(false);
  const [showHints, setShowHints] = useState(false);
  const [selfScore, setSelfScore] = useState<number | null>(null);
  const [categoryQuestions, setCategoryQuestions] = useState<Question[]>([]);
  const [currentQuestionIndex, setCurrentQuestionIndex] = useState<number>(-1);
  const { bookmarkedQuestions, toggleBookmark, addAnswer } = useUserStore();
  const { colors } = useTheme();
  
  useEffect(() => {
    const loadQuestion = async () => {
      try {
        const questionData = await getQuestionById(id);
        setQuestion(questionData || null);
        
        if (questionData) {
          // 加载同一分类的所有问题
          const questions = await getQuestionsByCategory(questionData.category);
          setCategoryQuestions(questions);
          
          // 找到当前问题在分类中的索引
          const index = questions.findIndex(q => q.id === id);
          setCurrentQuestionIndex(index);
        }
      } catch (error) {
        console.error('Error loading question:', error);
      } finally {
        setIsLoading(false);
      }
    };
    loadQuestion();
  }, [id]);
  
  // 处理导航到上一题
  const handlePrevQuestion = () => {
    if (currentQuestionIndex > 0 && categoryQuestions.length > 0) {
      // 清空用户回答和相关状态
      setUserAnswer("");
      setShowAnswer(false);
      setShowHints(false);
      setSelfScore(null);
      
      const prevQuestion = categoryQuestions[currentQuestionIndex - 1];
      router.push(`/question/${prevQuestion.id}`);
    }
  };
  
  // 处理导航到下一题
  const handleNextQuestion = () => {
    if (currentQuestionIndex < categoryQuestions.length - 1) {
      // 清空用户回答和相关状态
      setUserAnswer("");
      setShowAnswer(false);
      setShowHints(false);
      setSelfScore(null);
      
      const nextQuestion = categoryQuestions[currentQuestionIndex + 1];
      router.push(`/question/${nextQuestion.id}`);
    }
  };
  if (isLoading) {
    return (
      <View style={[styles.container, { backgroundColor: colors.background }]}>
        <Text style={[styles.loadingText, { color: colors.text }]}>加载中...</Text>
      </View>
    );
  }
  if (!question) {
    return (
      <View style={[styles.container, { backgroundColor: colors.background }]}>
        <Text style={[styles.errorText, { color: colors.text }]}>问题未找到</Text>
        <Button
          title="返回"
          onPress={() => router.back()}
          variant="outline"
        />
      </View>
    );
  }
  const isBookmarked = bookmarkedQuestions.includes(question.id);
  const difficultyInfo = difficulties.find((d) => d.id === question.difficulty);
  const handleToggleBookmark = () => {
    toggleBookmark(question.id);
  };
  const handleSubmitAnswer = () => {
    setShowAnswer(true);
  };
  const handleSaveProgress = (score: number) => {
    setSelfScore(score);
    addAnswer({
      questionId: question.id,
      userAnswer,
      score,
      timestamp: Date.now(),
    });
  };
  return (
    <SafeAreaView style={[styles.container, { backgroundColor: colors.background }]} edges={["bottom"]}>
      <Stack.Screen
        options={{
          title:
            question.category.charAt(0).toUpperCase() +
            question.category.slice(1),
          headerStyle: {
            backgroundColor: colors.background,
          },
          headerTintColor: colors.text,
          headerLeft: () => (
            <Pressable onPress={() => router.back()} style={styles.backButton}>
              <Ionicons name="arrow-back" size={24} color={colors.text} />
            </Pressable>
          ),
          headerRight: () => (
            <Pressable
              onPress={handleToggleBookmark}
              style={styles.bookmarkButton}
            >
              {isBookmarked ? (
                <Ionicons name="bookmark" size={24} color={colors.primary} />
              ) : (
                <Ionicons name="bookmark-outline" size={24} color={colors.text} />
              )}
            </Pressable>
          ),
        }}
      />
      <ScrollView showsVerticalScrollIndicator={false}>
        <View style={styles.header}>
          <View
            style={[
              styles.difficultyBadge,
              {
                backgroundColor: difficultyInfo?.color || colors.inactive,
              },
            ]}
          >
            <Text style={[styles.difficultyText, { color: colors.text }]}>
              {difficultyInfo?.name || question.difficulty}
            </Text>
          </View>
        </View>
        <Text style={[styles.questionText, { color: colors.text }]}>{question.question}</Text>
        {!showAnswer && (
          <>
            <View style={styles.answerContainer}>
              <Text style={[styles.answerLabel, { color: colors.text }]}>你的回答:</Text>
              <TextInput
                style={[styles.answerInput, { backgroundColor: colors.card, color: colors.text, borderColor: colors.border }]}
                multiline
                placeholder="想想这道题怎么写..."
                placeholderTextColor={colors.subtext}
                value={userAnswer}
                onChangeText={setUserAnswer}
              />
            </View>
            {question.hints && question.hints.length > 0 && (
              <View style={styles.hintsContainer}>
                <Pressable
                  style={styles.hintsToggle}
                  onPress={() => setShowHints(!showHints)}
                >
                  <Text style={[styles.hintsToggleText, { color: colors.primary }]}>
                    {showHints ? "隐藏提示" : "显示提示"}
                  </Text>
                </Pressable>
                {showHints && (
                  <View style={[styles.hintsList, { backgroundColor: "rgba(99, 102, 241, 0.1)" }]}>
                    {question.hints.map((hint, index) => (
                      <Text key={index} style={[styles.hintText, { color: colors.text }]}>
                        • {hint}
                      </Text>
                    ))}
                  </View>
                )}
              </View>
            )}
            <Button
              title="提交答案"
              onPress={handleSubmitAnswer}
              disabled={userAnswer.trim().length === 0}
              fullWidth
            />
          </>
        )}
        {showAnswer && (
          <View style={styles.solutionContainer}>
            <Text style={[styles.solutionLabel, { color: colors.text }]}>看看参考答案:</Text>
            <Text style={[styles.solutionText, { color: colors.text, backgroundColor: colors.card, borderColor: colors.border }]}>{question.answer}</Text>
            {question.relatedLinks && question.relatedLinks.length > 0 && (
              <View style={styles.linksContainer}>
                <Text style={[styles.linksLabel, { color: colors.text }]}>Related Resources:</Text>
                {question.relatedLinks.map((link, index) => (
                  <View key={index} style={styles.linkItem}>
                    <Ionicons name="open-outline" size={16} color={colors.primary} />
                    <Text style={[styles.linkText, { color: colors.primary }]}>{link}</Text>
                  </View>
                ))}
              </View>
            )}
            {selfScore === null && (
              <View style={[styles.selfScoreContainer, { backgroundColor: colors.card, borderColor: colors.border }]}>
                <Text style={[styles.selfScoreLabel, { color: colors.text }]}>
                  你觉得自己回答的咋样？
                </Text>
                <View style={styles.scoreButtons}>
                  <Button
                    title="我不造啊..."
                    variant="outline"
                    size="small"
                    onPress={() => handleSaveProgress(25)}
                  />
                  <Button
                    title="还行吧"
                    variant="outline"
                    size="small"
                    onPress={() => handleSaveProgress(50)}
                  />
                  <Button
                    title="自我感觉良好！"
                    variant="outline"
                    size="small"
                    onPress={() => handleSaveProgress(75)}
                  />
                  <Button
                    title="不愧是我！"
                    variant="outline"
                    size="small"
                    onPress={() => handleSaveProgress(100)}
                  />
                </View>
              </View>
            )}
            {selfScore !== null && (
              <View style={[styles.savedContainer, { backgroundColor: "rgba(16, 185, 129, 0.1)" }]}>
                <Text style={[styles.savedText, { color: colors.success }]}>
                  进度已保存，你给自己的评分为： {selfScore}分.
                </Text>
              </View>
            )}
          </View>
        )}
        <View style={styles.navigationContainer}>
          <Button
            title="上一题"
            onPress={handlePrevQuestion}
            disabled={currentQuestionIndex <= 0}
            variant="outline"
            size="small"
            icon={<Ionicons name="arrow-back" size={16} color={currentQuestionIndex <= 0 ? colors.inactive : colors.primary} />}
          />
          <Text style={[styles.navigationText, { color: colors.subtext }]}>
            {currentQuestionIndex + 1} / {categoryQuestions.length}
          </Text>
          <Button
            title="下一题"
            onPress={handleNextQuestion}
            disabled={currentQuestionIndex >= categoryQuestions.length - 1}
            variant="outline"
            size="small"
            icon={<Ionicons name="arrow-forward" size={16} color={currentQuestionIndex >= categoryQuestions.length - 1 ? colors.inactive : colors.primary} />}
          />
        </View>
        <View style={styles.footer} />
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 16,
  },
  backButton: {
    padding: 8,
  },
  bookmarkButton: {
    padding: 8,
  },
  navigationContainer: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    marginTop: 24,
    marginBottom: 16,
  },
  navigationText: {
    fontSize: 14,
    fontWeight: "500",
  },
  header: {
    flexDirection: "row",
    marginBottom: 16,
  },
  difficultyBadge: {
    paddingHorizontal: 12,
    paddingVertical: 6,
    borderRadius: 4,
  },
  difficultyText: {
    fontSize: 14,
    fontWeight: "600",
  },
  questionText: {
    fontSize: 18,
    fontWeight: "600",
    marginBottom: 24,
    lineHeight: 26,
  },
  answerContainer: {
    marginBottom: 24,
  },
  answerLabel: {
    fontSize: 16,
    fontWeight: "600",
    marginBottom: 8,
  },
  answerInput: {
    borderRadius: 8,
    padding: 16,
    minHeight: 150,
    fontSize: 16,
    textAlignVertical: "top",
    borderWidth: 1,
  },
  hintsContainer: {
    marginBottom: 24,
  },
  hintsToggle: {
    alignSelf: "flex-start",
  },
  hintsToggleText: {
    fontSize: 16,
    fontWeight: "600",
  },
  hintsList: {
    marginTop: 12,
    borderRadius: 8,
    padding: 16,
  },
  hintText: {
    fontSize: 14,
    marginBottom: 8,
  },
  solutionContainer: {
    marginTop: 24,
  },
  solutionLabel: {
    fontSize: 18,
    fontWeight: "600",
    marginBottom: 12,
  },
  solutionText: {
    fontSize: 16,
    lineHeight: 24,
    borderRadius: 8,
    padding: 16,
    borderWidth: 1,
  },
  linksContainer: {
    marginTop: 24,
  },
  linksLabel: {
    fontSize: 16,
    fontWeight: "600",
    marginBottom: 12,
  },
  linkItem: {
    flexDirection: "row",
    alignItems: "center",
    marginBottom: 8,
  },
  linkText: {
    fontSize: 14,
    marginLeft: 8,
    textDecorationLine: "underline",
  },
  selfScoreContainer: {
    marginTop: 24,
    borderRadius: 8,
    padding: 16,
    borderWidth: 1,
  },
  selfScoreLabel: {
    fontSize: 16,
    fontWeight: "600",
    marginBottom: 16,
    textAlign: "center",
  },
  scoreButtons: {
    flexDirection: "row",
    justifyContent: "space-between",
  },
  savedContainer: {
    marginTop: 24,
    borderRadius: 8,
    padding: 16,
  },
  savedText: {
    fontSize: 14,
    textAlign: "center",
  },
  errorText: {
    fontSize: 18,
    marginBottom: 24,
    textAlign: "center",
  },
  loadingText: {
    fontSize: 18,
    marginBottom: 24,
    textAlign: "center",
  },
  footer: {
    height: 40,
  },
});
